package com.itheima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.search.SearchConstants;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dto.UserSearchDto;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import com.itheima.search.feign.BehaviorFeign;
import com.itheima.search.service.ApUserSearchService;
import com.itheima.search.service.ArticleSearchService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @作者 itcast
 * @创建日期 2020/12/22 9:44
 **/
@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private BehaviorFeign behaviorFeign;

    @Autowired
    private ApUserSearchService apUserSearchService;
    /**
     * 搜索文章
     * @param dto
     * @return
     * @throws IOException
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //1.检查参数
        if (dto == null || StringUtils.isBlank(dto.getSearchWords())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 如果是首页查询  则记录搜索关键字
        if (dto.getFromIndex() == 0) {
            // 这里因为insert方法被标记了异步处理注解
            // 所以会使用全局线程池执行一个新的线程任务
            // 因为会新创建一个线程，所以提前把线程里的用户信息取出来
            apUserSearchService.insert(getEntry(dto),dto.getSearchWords());
        }
        //2.从es中检索数据
        SearchRequest searchRequest = new SearchRequest(SearchConstants.SEARCH_ARTICLE_INDEX_NAME);
        //条件构建器
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //根据关键字分词查询
        QueryStringQueryBuilder queryBuilder = QueryBuilders.queryStringQuery(dto.getSearchWords()).field("title").defaultOperator(Operator.OR);
        boolQueryBuilder.must(queryBuilder);
        //查询小于mindate的数据
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime());
        boolQueryBuilder.filter(rangeQueryBuilder);
        searchSourceBuilder.query(boolQueryBuilder);
        //按照发布时间倒序
        searchSourceBuilder.sort("publishTime", SortOrder.DESC);
        //分页
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(dto.getPageSize());
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //3.结果数据，封装返回

        List<Map> articleList = new ArrayList<>();

        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            Map map = JSON.parseObject(sourceAsString, Map.class);
            articleList.add(map);
        }
        return ResponseResult.okResult(articleList);
    }

    /**
     * 查询行为实体
     * @param dto
     * @return
     */
    private ApBehaviorEntry getEntry(UserSearchDto dto) {
        return behaviorFeign.findByUserIdOrEntryId(AppThreadLocalUtils.getUser().getId(), dto.getEquipmentId());
    }
}
